import jwt
from django.conf import settings
from django.http import JsonResponse

from tools.myjwt import mjwt


class TokenVerificationMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 处理请求的逻辑
        response = self.process_request(request)
        if response:
            return response
        return self.get_response(request)

    def process_request(self, request):
        # 检查是否需要Token验证，例如排除某些路径
        if request.path in getattr(settings, 'TOKEN_EXEMPT_PATHS', []):
            return None

        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return JsonResponse({'error': 'Authorization header is required'}, status=401)

        token_type, token = auth_header.split()
        if token_type.lower() != 'bearer':
            return JsonResponse({'error': 'Bearer token is required'}, status=401)

        try:
            # 使用mjwt解码Token
            payload = mjwt.jwt_decode(token)
        except jwt.ExpiredSignatureError:
            return JsonResponse({'error': 'Token has expired'}, status=401)
        except jwt.InvalidTokenError:
            return JsonResponse({'error': 'Invalid token'}, status=401)

        # 如果Token验证成功，可以将其添加到request中
        request.user = payload  # 或者根据payload中的信息获取用户对象

        return None
